package com.reading.common.constant;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author guwenqi_1995@163.com
 * @projectName alone-reading
 * @description: TODO
 * @date 2019/8/8 15:43
 */
@Slf4j
@Getter
@AllArgsConstructor
public enum NumberEnum {

    ZERO(0, "0", "零"),
    ONE(1, "1", "一"),
    TWO(2, "2", "二"),
    THREE(3, "3", "三"),
    FOUR(4, "4", "四"),
    FIVE(5, "5", "五"),
    SIX(6, "6", "六"),
    SEVER(7, "7", "七"),
    EIGHT(8, "8", "八"),
    NINE(9, "9", "九"),


    ;

    private Integer code;

    private String number;

    private String numberChinese;

    private static final String[] CountingUnit = {"", "十", "百", "千", "万", "十", "百",
            "千", "亿", "十", "百", "千"};

    private static String getNumberChinese(Integer number) {
        for (NumberEnum numberEnum : NumberEnum.values()) {
            if (numberEnum.getCode().equals(number)) {
                return numberEnum.getNumberChinese();
            }
        }
        return ZERO.getNumberChinese();
    }

    private static String getNumberChinese(String number) {
        for (NumberEnum numberEnum : NumberEnum.values()) {
            if (numberEnum.getNumber().equals(number)) {
                return numberEnum.getNumberChinese();
            }
        }
        return ZERO.getNumberChinese();
    }

    /**
     * 阿拉伯数字 转 汉字数字
     *
     * @param number
     * @return 汉字数字
     */
    public static String numberToString(Integer number) {
        String numberContent = number.toString();

        List<String> contents = new ArrayList<>();
        for (int i = 0; i < numberContent.length(); i++) {
            contents.add(numberContent.substring(i, i + 1));
        }

        int index = 0;
        StringBuffer numberBuffer = new StringBuffer();
        for (int i = contents.size() - 1; i >= 0; i--) {
            String numberChinese = getNumberChinese(contents.get(index));

            if (numberBuffer.length() >= 1) {
                if (numberBuffer.substring(numberBuffer.length() - 1, numberBuffer.length())
                        .equals(ZERO.getNumberChinese())
                        && numberChinese.equals(ZERO.getNumberChinese())) {
                    index++;
                    continue;
                }
            }
            numberBuffer.append(numberChinese);
            if (numberChinese.equals(ZERO.getNumberChinese())) {
                index++;
                continue;
            }

            numberBuffer.append(CountingUnit[i]);
            index++;
        }

        numberContent = numberBuffer.substring(numberBuffer.length() - 1, numberBuffer.length())
                    .equals(ZERO.getNumberChinese()) ?
                numberBuffer.substring(0, numberBuffer.length() - 1) : numberBuffer.toString();


        log.info("Conver Number to String : {}", numberContent);

        return numberBuffer.toString();
    }
}
